<template>
  <div>
    <el-row>
      <el-col :span="8" style="border-right: 3px solid #dcdfe6; padding-right: 5px">
        <p class="pinformation">样品搜索条件</p>
        <el-form label-width="80" ref="queryRef" :model="queryParams">
          <el-row>
            <el-col :span="8">
              <el-form-item label="方案编号：" prop="projectCode">
                <el-input maxlength="100" clearable v-model="queryParams.projectCode" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="方案名称：" prop="projectName">
                <el-input maxlength="100" clearable v-model="queryParams.projectName" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交接批次：" prop="withNumber">
                <el-input maxlength="100" clearable v-model="queryParams.withNumber" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="检测项目：" prop="jcxmName">
                <el-input maxlength="100" clearable v-model="queryParams.jcxmName" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="样品编号：" prop="sampleCode">
                <el-input maxlength="100" clearable v-model="queryParams.sampleCode" @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-row justify="center">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <p class="pinformation" style="margin-top: 8.5px">待测样品列表</p>
          <p class="totalStyle" style="margin-top: 6px">
            共 {{ total }} 条数据
          </p>
          <el-row style="margin-left: 25px">
            <el-button link type="success" icon="plus" @click="handleBatchSelection"
              :disabled="!selectData.sJIds?.length">批量选择</el-button>
          </el-row>
        </el-row>
        <el-scrollbar :height="height" ref="scrollbarRef">
          <el-tree show-checkbox :data="treeData" :props="defaultProps" :default-expand-all="true" @check="checkChange"
            node-key="sJId" v-loading="treeLoading" :highlight-current="true" ref="treeRef" />
        </el-scrollbar>
      </el-col>
      <el-col :span="16" style="padding-left: 5px">
        <el-row style="justify-content: space-between">
          <el-row>
            <el-form-item label="方法编号：" prop="" style="margin-bottom: 0px !important">
              {{ infoForm.methodCode }}
            </el-form-item>
            <el-form-item label="方法名称：" prop="" style="margin-bottom: 0px !important; margin-left: 15px">
              <span v-html="proxy.getSupAndSub(infoForm.methodName)"></span>
            </el-form-item>
            <el-button link type="success" icon="plus" style="margin-left: 15px" @click="handleMethodChange"
              v-if="lMId">更改方法</el-button>
          </el-row>
        </el-row>
        <el-form :model="numForm" label-width="90" ref="numRef" :disabled="isDisabled">
          <el-row>
            <el-col :span="6">
              <el-form-item label="实验室空白：" prop="methodCode">
                <el-input-number maxlength="100" clearable :min="0" @change="numberChange(1, $event)"
                  style="width: 100%" placeholder="请输入实验室空白" v-model="numForm.qc_1" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="试剂空白：" prop="methodCode">
                <el-input-number maxlength="100" clearable :min="0" @change="numberChange(9, $event)"
                  style="width: 100%" placeholder="请输入试剂空白" v-model="numForm.qc_9" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="容器空白：" prop="methodCode">
                <el-input-number maxlength="100" clearable :min="0" style="width: 100%"
                  @change="numberChange(10, $event)" placeholder="请输入容器空白" v-model="numForm.qc_10" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="中间点核查：" prop="methodCode">
                <el-input-number maxlength="100" clearable :min="0" style="width: 100%" placeholder="请输入中间点核查"
                  v-model="numForm.qc_4" @change="numberChange(4, $event)" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="零点核查：" prop="methodCode">
                <el-input-number maxlength="100" clearable :min="0" style="width: 100%" placeholder="请输入零点核查"
                  v-model="numForm.qc_7" @change="numberChange(7, $event)" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="对照：" prop="methodCode">
                <el-input-number maxlength="100" clearable :min="0" style="width: 100%" placeholder="请输入对照"
                  v-model="numForm.qc_8" @change="numberChange(8, $event)" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-button type="success" @click="handleBlind" style="margin-left:15px">选取自控盲样</el-button>
              <el-button type="success">选取自制溶液</el-button>
            </el-col>
          </el-row>
        </el-form>
        <p class="pinformation">搜索条件</p>
        <el-form label-width="80" ref="queryRightRef" :model="queryRightParams">
          <el-row>
            <el-col :span="6">
              <el-form-item label="方案编号：" prop="projectCode">
                <el-input maxlength="100" clearable placeholder="请输入方案编号" v-model="queryRightParams.projectCode"
                  @keyup.enter="handleSelectQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方案名称：" prop="projectName">
                <el-input maxlength="100" clearable placeholder="请输入方案名称" v-model="queryRightParams.projectName"
                  @keyup.enter="handleSelectQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品编号：" prop="sampleCode">
                <el-input maxlength="100" clearable placeholder="请输入样品编号" v-model="queryRightParams.sampleCode"
                  @keyup.enter="handleSelectQuery" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="检测项目：" prop="jcxmName">
                <el-input maxlength="100" clearable placeholder="请输入检测项目" v-model="queryRightParams.jcxmName"
                  @keyup.enter="handleSelectQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-row justify="center">
                <el-button type="success" @click="handleSelectQuery">搜索</el-button>
                <el-button class="business resetBtn" @click="resetSelectQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
        <el-row>
          <el-button :disabled="!YySJId.length" link type="success" icon="plus" style="margin-left: 15px"
            @click="handlePxyOrJb(null, 14)">批量平行</el-button>
          <el-button :disabled="!YySJId.length" link type="success" icon="plus" style="margin-left: 15px"
            @click="handlePxyOrJb(null, 3)">批量加标</el-button>
          <el-button :disabled="!YySJId.length" link type="success" icon="plus"
            style="margin-left: 15px">批量替代物</el-button>
        </el-row>
        <el-row>
          <p class="pinformation" style="margin-top: 8.5px">已选样品列表</p>
          <p class="totalStyle" style="margin-top: 6px">
            共 {{ selectedTotal }} 条数据
          </p>
          <el-row>
            <el-form-item label="方案总数：" prop="" style="margin-bottom: 0px !important; margin-left: 15px">
              {{ countForm.projectCount }}
            </el-form-item>
            <el-form-item label="样品编号数：" prop="" style="margin-bottom: 0px !important; margin-left: 15px">
              {{ countForm.sampleCount }}
            </el-form-item>
            <el-form-item label="检测项目数：" prop="" style="margin-bottom: 0px !important; margin-left: 15px">
              {{ countForm.jcxmCount }}
            </el-form-item>
            <el-button link type="success" icon="plus" style="margin-left: 15px"
              @click="handleExport">导出excel</el-button>
            <el-button link type="danger" icon="plus" style="margin-left: 15px; color: #f56c6c !important"
              @click="handleDel()" :disabled="!sJIds.length">批量删除</el-button>
          </el-row>
        </el-row>
        <el-table ref="mainTableRef" :data="selectedList" v-loading="selectedLoading"
          @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" width="55" align="center" :selectable="selectable1" />
          <el-table-column show-overflow-tooltip label="样品编号" align="center" prop="sampleCode" />
          <el-table-column show-overflow-tooltip label="检测项目" align="center" prop="jcxmName" width="120">
            <template #default="scope">
              <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="检测类型" align="center" prop="jclbName"  width="130"/>
          <el-table-column show-overflow-tooltip label="方案编号" align="center" prop="projectCode"  width="150"/>
          <el-table-column label="操作" align="center" width="400">

            <template #default="scope">
              <el-button link type="success" @click="handlePxyOrJb(scope.row, 14)" v-if="scope.row.sampleType == -1 ||
        scope.row.sampleType == 0 ||
        scope.row.sampleType == 11 ||
        scope.row.sampleType == 12 ||
        scope.row.sampleType == 51
        ">平行</el-button>
              <el-button link type="success" @click="handlePxyOrJb(scope.row, 3)" v-if="scope.row.sampleType == -1 ||
        scope.row.sampleType == 0 ||
        scope.row.sampleType == 11 ||
        scope.row.sampleType == 12 ||
        scope.row.sampleType == 51
        ">加标</el-button>
              <el-button link type="success" @click="handleSubstitutes(scope.row)" v-if="scope.row.sampleType == -1 ||
        scope.row.sampleType == 0 ||
        scope.row.sampleType == 11 ||
        scope.row.sampleType == 12 ||
        scope.row.sampleType == 51
        ">替代物</el-button>
              <el-button link type="success" @click="handleSamePxyOrJb(scope.row, 14)" v-if="scope.row.sampleType == -1 ||
        scope.row.sampleType == 0 ||
        scope.row.sampleType == 11 ||
        scope.row.sampleType == 12 ||
        scope.row.sampleType == 51
        ">编号平行</el-button>
              <el-button link type="success" @click="handleSamePxyOrJb(scope.row, 3)" v-if="scope.row.sampleType == -1 ||
        scope.row.sampleType == 0 ||
        scope.row.sampleType == 11 ||
        scope.row.sampleType == 12 ||
        scope.row.sampleType == 51
        ">编号加标</el-button>
              <el-button link type="success" @click="handlePxyOrJb(scope.row, 2)" v-if="scope.row.sampleType == 1
        ">空白加标</el-button>
        <el-button link type="success" @click="handlePxyOrJb(scope.row, 19)" v-if="scope.row.isCt == 0 && (scope.row.sampleType == -1 ||
        scope.row.sampleType == 0 ||
        scope.row.sampleType == 11 ||
        scope.row.sampleType == 12 ||
        scope.row.sampleType == 51)
        ">穿透</el-button>
              <!-- scope.row.sampleType:1说明是实验室空白、中间核查那几项只能从上面删除不能从这里删除。 -->
              <el-button link type="success" @click="handleDel(scope.row)"
                v-if="(scope.row.getId && scope.row.sampleType != 51) || (scope.row.sampleType != 51 && scope.row.sampleType != 1 && scope.row.sampleType != 4 && scope.row.sampleType != 7 && scope.row.sampleType != 8 && scope.row.sampleType != 9 && scope.row.sampleType != 10)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="selectedTotal > 0" :total="selectedTotal" v-model:page="queryRightParams.pageNum"
          v-model:limit="queryRightParams.pageSize" @pagination="getSelectedListView" />
      </el-col>
    </el-row>
    <el-dialog :class="'el-dialog-theme3'" title="添加替代物" v-model="open" width="500px" append-to-body
      draggable :close-on-click-modal="false">
      <el-form-item label="检测方法：" prop="methodName">
        {{ substitutesForm.methodCode }}<span v-html="proxy.getSupAndSub(substitutesForm.methodName)"></span>
      </el-form-item>
      <el-form-item label="检测项目：" prop="jcxmName">
        <el-select clearable v-model="substitutesForm.mJIds" style="width: 100%" multiple :multiple-limit="2">
          <el-option v-for="item of jcxmList" :key="item.mJId" :label="item.jcxmName + '(' + item.jclbName + ')'" :value="item.mJId">
            <span v-html="proxy.getSupAndSub(item.jcxmName)"></span>({{ item.jclbName }})
          </el-option>
        </el-select>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleTdwDefine">确 定</el-button>
          <el-button type="danger" @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="myOpen" :title="myTitle" width="1200px" @close="dialogClose">
      <p class="pinformation">质控样搜索条件</p>
      <el-row>
        <el-col :span="5">
          <el-form-item label="唯一编号：" prop="bzwzCode">
            <el-input maxlength="100" clearable placeholder="请输入唯一编号" v-model="qualityForm.bzwzCode"
              @keyup.enter="handlequalityQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="标准物质：" prop="bzwzName" label-width="90">
            <el-input maxlength="100" clearable placeholder="请输入标准物质" v-model="qualityForm.bzwzName"
              @keyup.enter="handlequalityQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="检测项目类型：" prop="isSingle" label-width="110">
            <el-select placeholder="请选择" clearable v-model="qualityForm.isSingle" filterable>
              <el-option v-for="dict in sys_bzwz_jcxm_type" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-row style="justify-content: center">
            <el-radio label="0" v-model="qualityForm.isLike">模糊搜索</el-radio>
            <el-radio label="1" v-model="qualityForm.isLike">精准搜索</el-radio>
          </el-row>
        </el-col>
        <el-col :span="4">
          <el-row justify="center">
            <el-button type="success" @click="handlequalityQuery">搜索</el-button>
            <el-button class="business resetBtn" @click="handlequalityReset">重置</el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <p class="pinformation">质控样搜索结果列表</p>
        <p class="totalStyle">共 {{ total2 }} 条数据</p>
      </el-row>
      <el-table :data="qualityList" border ref="qualityTable" @row-click="qualityRowClick" height="20vh">
        <el-table-column label="唯一性编号" align="center" prop="bzwzCode" />
        <el-table-column label="标准物质名称" align="center" prop="bzwzName" />
        <el-table-column label="批次号" align="center" prop="produceCode" />
        <el-table-column label="有效日期" align="center" prop="yxDate" />
        <el-table-column label="类型" align="center" prop="bzwzType">

          <template #default="scope">
            <dict-tag :options="sys_bzwz_type" :value="scope.row.bzwzType" />
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <p class="pinformation">检测项目列表</p>
        <p class="totalStyle">共 {{ total3 }} 条数据</p>
      </el-row>
      <el-table :data="qualityJcxmList" border ref="qualityTable" @selection-change="selectionChange" height="20vh">
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="检测项目" align="center" prop="jcxmName" width="150">

          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="浓度值" align="center" prop="con" width="100">

          <template #default="scope">{{ scope.row.con
            }}{{ scope.row.conUnitName }}</template></el-table-column>
        <el-table-column label="不确定度值" align="center" prop="notvalue" width="100">

          <template #default="scope">{{
        scope.row.notvalue }}{{ scope.row.subNotvalueName }}</template></el-table-column>
        <el-table-column label="检测类别" align="center" width="150">

          <template #default="scope">
            <el-select v-model="scope.row.jclbId" filterable @change="jclbIdChange(scope.row)">
              <el-option v-for="item in jclbList" :key="item.jclbId" :label="item.jclbName"
                :value="item.jclbId"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="检测方法" align="center">

          <template #default="scope">
            {{ scope.row.methodContent }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-row style="justify-content: end">
            <el-form-item label="盲样编号：" prop="methodCode">
              <onlinePreview :typeId="serialTypeId" @emitForm="emitForm" :paramsData="{ lMId: lMId }"
                ref="onlinePreviewRef"></onlinePreview>
            </el-form-item>
            <el-button type="success" @click="handleDefine" style="margin-left: 15px"
              :disabled="!qualityJcxmIdList.length">确定</el-button>
            <el-button type="danger" @click="myOpen = false">关闭</el-button>
          </el-row>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="changeOpen" title="更改方法" width="950px" @close="changeDialogClose">
      <el-form ref="formRef" :model="changeForm" @submit.native.prevent>
        <el-form-item label="选择方法：" prop="methodId">
          <el-select v-model="changeForm.methodId" filterable placeholder="请选择" style="width: 100%">
            <el-option v-for="(item, index) in methodList" :key="index" :label="item.methodCode + '　' + item.methodName"
              :value="item.methodId" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleConfime">确定</el-button>
          <el-button type="danger" @click="changeOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import onlinePreview from "@/components/onlinePreview/index.vue";

import {
  getXzzkTree,
  checkTreeNodes,
  getSelectedList,
  delSelectedList,
  getSelectView,
  getSubstitutes,
  addTdw,
  addPxy,
  addSamePxy,
  getNumberForm,
  addNumber,
  listQuality,
  listQualityJcxm,
  listJclb,
  sampleListCount,
  changeMethod,
  saveMethod,
} from "@/api/lab/labMethod";

import { listMethod, postMethod } from "@/api/sampleManage/sampleQc";

import { nextTick, onMounted, watch } from "vue";
import { getToken } from '@/utils/auth'

const { proxy } = getCurrentInstance();
const queryParams = ref({});
const queryRightParams = ref({ pageNum: 1, pageSize: 10 });
const numForm = ref({});
const infoForm = ref({});
const substitutesForm = ref({});
const total = ref(0);
const selectedTotal = ref(0);
const selectedList = ref([]);
const jcxmList = ref([]);
const selectedLoading = ref(false);
const treeLoading = ref(false);
const height = ref(0);
const treeData = ref([]);
const open = ref(false);
const changeOpen = ref(false);
const changeForm = ref({ flagStatus: 0 });

const myOpen = ref(false);
const myTitle = ref("");
const qualityForm = ref({ isLike: "0" });
const form = ref({ params: {} });
const total2 = ref(0);
const total3 = ref(0);
const qualityList = ref([]);
const qualityJcxmList = ref([]);
const qualityJcxmIdList = ref([]);
const jclbList = ref([]);
const serialTypeId = ref(30);
const onlinePreviewRef = ref(ref);
const countForm = ref({
  projectCount: 0,
  jcxmCount: 0,
  sampleCOunt: 0,
});
const { sys_bzwz_type, sys_bzwz_jcxm_type } = proxy.useDict(
  "sys_bzwz_type",
  "sys_bzwz_jcxm_type"
);

const defaultProps = ref({
  label: "jcxmName",
});

const parentId = ref("");
const lMId = ref("");
const projectId = ref("");

// ------------------------盲样操作------------------------
function dialogClose() {
  qualityJcxmList.value = [];
  qualityList.value = [];
  qualityForm.value = { isLike: "0" };
  total3.value = 0;
  total2.value = 0;
  bzwzId.value = "";
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("/lims/labMethod/export", {
    ...queryRightParams.value,
  }, `样品列表_${new Date().getTime()}.xlsx`);
};
function handlequalityQuery() {
  let opt = JSON.parse(JSON.stringify(qualityForm.value))
  opt.lMId = lMId.value
  listQuality(opt).then((res) => {
    qualityList.value = res.data;
    total2.value = res.data.length;
  });
}

function handlequalityReset() {
  qualityForm.value = { isLike: "0" };
  handlequalityQuery();
}

const bzwzId = ref("");

function qualityRowClick(row) {
  listQualityJcxm(row.bzwzId).then((res) => {
    qualityJcxmList.value = res.data;
    total3.value = res.data.length;
    listJclb(lMId.value).then((res) => {
      jclbList.value = res.data;
      bzwzId.value = row.bzwzId;
      if (jclbList.value.length == 1) {
        qualityJcxmList.value.forEach((item) => {
          item.jclbId = jclbList.value[0].jclbId;
          listMethod({
            jclbId: jclbList.value[0].jclbId,
            bucketId: item.bucketId,
          }).then((res1) => {
            item.methodList = res1.data;
            for (let i = 0; i < item.methodList.length; i++) {
              if (item.methodList[i].methodId == infoForm.value.methodId) {
                item.mJId = item.methodList[i].mJId
                item.methodContent = item.methodList[i].methodName
                break
              } else {
                delete item.mJId
                delete item.methodContent
              }
            }
          });
        });
      }
    });
  });
}

function selectionChange(selection) {
  qualityJcxmIdList.value = selection;
}

function selectable(row) {
  if (row.jclbId && row.mJId) {
    return true;
  } else {
    return false;
  }
}

function selectable1(row) {
  if (row.sampleType === 1 || row.sampleType === 9 || row.sampleType === 10 || row.sampleType === 9
   || row.sampleType === 4 || row.sampleType === 7 || row.sampleType === 8 ) {
    return false;
  } else {
    return true;
  }
}

function jclbIdChange(row) {
  row.methodList = [];
  row.mJId = "";
  row.methodContent = "";
  if (!row.jclbId) return;
  listMethod({ jclbId: row.jclbId, bucketId: row.bucketId }).then((res) => {
    row.methodList = res.data;
    for (let i = 0; i < row.methodList.length; i++) {
      if (row.methodList[i].methodId == infoForm.value.methodId) {
        row.mJId = row.methodList[i].mJId
        row.methodContent = row.methodList[i].methodName
        break
      }
    }
  });
}

function emitForm(val) {
  form.value.params = {};
  form.value.params["serialData"] = val;
}

function handleDefine() {
  form.value.lMId = lMId.value;
  form.value.bzwzId = bzwzId.value;
  form.value.projectSampleJcxmList = qualityJcxmIdList.value.map((item) => {
    return {
      bJId: item.bJId, jclbId: item.jclbId, mJId: item.mJId,
      bzwzId: item.bzwzId, bzwzValue: item.con,
      bzwzValueUnit: item.conUnitName,
      bzwzNotvalue: item.notvalue,
      bzwzNotvalueUnit: item.subNotvalueName
    };
  });
  postMethod(form.value).then((res) => {
    myOpen.value = false;
    proxy.$modal.msgSuccess("保存成功");
    getSelectedListView();
    handleSampleListCount();
  });
}

function handleBlind() {
  myOpen.value = true;
  myTitle.value = "盲样";
  let opt = JSON.parse(JSON.stringify(qualityForm.value))
  opt.lMId = lMId.value
  listQuality(opt).then((res) => {
    qualityList.value = res.data;
    total2.value = res.data.length;
  });
}

// ----------------------------------------------

defineExpose({
  parentId,
  lMId,
  projectId,
  getSelectedListView,
  handleSampleListCount,
  getList,
  getNumber,
  getSelectForm,
  selectedTotal,
});

function handleQuery() {
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectQuery() {
  queryRightParams.value.pageNum = 1;
  getSelectedListView();
}

function resetSelectQuery() {
  proxy.resetForm("queryRightRef");
  handleSelectQuery();
}

function getList() {
  queryParams.value.lMId = parentId.value;
  if (projectId.value) {
    queryParams.value.projectId = projectId.value;
  }
  treeLoading.value = true;
  getXzzkTree(queryParams.value).then((res) => {
    if (res.data) {
      treeData.value = res.data.treeData;
      total.value = res.data.count;
    } else {
      treeData.value = [];
      total.value = 0;
    }
    treeLoading.value = false;
    getHeight();
  });
}

const selectData = ref({});

function checkChange(row, selection) {
  selectData.value.sJIds = [];
  selection.checkedNodes.forEach((item) => {
    if (item.treeType === 3) {
      selectData.value.sJIds.push(item.sJId);
    }
  });
}

function handleBatchSelection() {
  selectData.value.parentId = parentId.value;
  if (projectId.value) {
    selectData.value.projectId = projectId.value;
  }
  if (lMId.value) {
    selectData.value.lMId = lMId.value;
  }
  checkTreeNodes(selectData.value).then((res) => {
    if (!lMId.value) {
      lMId.value = res.data;
      emit("lMId", res.data);
    }
    getSelectedListView();
    getList();
    handleSampleListCount();
  });
}

function handleTdwDefine() {
  addTdw(substitutesForm.value).then((res) => {
    open.value = false;
    proxy.$modal.msgSuccess("保存成功");
    getSelectedListView();
    handleSampleListCount();
  });
}

function numberChange(bs, newVal) {
  addNumber({ sampleType: bs, lMId: lMId.value, count: newVal }).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    getSelectedListView();
    handleSampleListCount();
  });
}

function getNumber() {
  getNumberForm(lMId.value ? lMId.value : parentId.value).then((res) => {
    numForm.value.qc_1 = 0;
    numForm.value.qc_10 = 0;
    numForm.value.qc_4 = 0;
    numForm.value.qc_7 = 0;
    numForm.value.qc_8 = 0;
    numForm.value.qc_9 = 0;
    res.data.forEach((item) => {
      numForm.value[`qc_` + item.sampleType] = item.count;
    });
  });
}

//统计已选样品的方案数、样品编号数、检测项目数
function handleSampleListCount() {
  //如果if条件成立，则说明当前列表中的样品全部删除了，此时lmId.value的值也会变成空的。
  if (!lMId.value || lMId.value.length == 0) {
    countForm.value.projectCount = 0;
    countForm.value.sampleCount = 0;
    countForm.value.jcxmCount = 0;
    return;
  }
  sampleListCount(lMId.value).then((res) => {
    countForm.value = res.data;
  });
}
function getSelectedListView() {
  if (!lMId.value) return;
  selectedLoading.value = true;
  queryRightParams.value.lMId = lMId.value;
  getSelectedList(queryRightParams.value).then((res) => {
    selectedList.value = res.rows;
    selectedTotal.value = res.total;
    selectedLoading.value = false;
    if(selectedTotal.value == 0){
      emit("setMyIdEmpty");
    }
  });
}

function getSelectForm() {
  getSelectView(lMId.value ? lMId.value : parentId.value).then((res) => {
    infoForm.value = res.data;
  });
}

const sJIds = ref([]);
const YySJId = ref([]);
function handleSelectionChange(selection) {
  sJIds.value = selection.map((item) => {
    return item.sJId;
  });
  YySJId.value = [];
  selection.forEach((item) => {
    //51:现场拆分的样品
    if (item.sampleType == -1 || item.sampleType == 51 || item.sampleType == 0 || item.sampleType == 11)
      YySJId.value.push(item.sJId);
  });
}

function handlePxyOrJb(row, sampleType) {
  let params = {
    sampleType: sampleType,
    sJIds: row ? [row.sJId] : YySJId.value,
  };
  addPxy(params).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    getSelectedListView();
    handleSampleListCount();
  });
}

function handleSamePxyOrJb(row, sampleType) {
  let params = {
    sampleType: sampleType,
    sJIds: row ? [row.sJId] : YySJId.value,
  };
  addSamePxy(params).then((res) => {
    proxy.$modal.msgSuccess("保存成功");
    getSelectedListView();
    handleSampleListCount();
  });
}



function handleDel(row) {
  if(!lMId.value){
    proxy.$modal.msgError("删除失败，请刷新页面后重新删除！");
    return;
  }
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    let params = {
      parentId: parentId.value,
      lMId: lMId.value,
      sJIds: row ? [row.sJId] : sJIds.value,
    };
    delSelectedList(params).then((res) => {
      if (res.data == "-1") {
        lMId.value = "";
        emit("lMId", "");
        selectedList.value = [];
        selectedTotal.value = 0;
        emit("setMyIdEmpty");
      }
      proxy.$modal.msgSuccess("删除成功");
      getSelectedListView();
      getList();
      handleSampleListCount();
    });
  });
}

function handleSubstitutes(row) {
  open.value = true;
  getSubstitutes(row.sJId).then((res) => {
    substitutesForm.value = res.data.method;
    substitutesForm.value.sJId = row.sJId;
    jcxmList.value = res.data.jcxmList;
  });
}

const heightParams = ref([{ tableName: "main", bottomHeight: 105 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

onMounted(() => {
  nextTick(function () {
    let number = document.getElementsByClassName("el-input-number");
    for (let i = 0; i < number.length; i++) {
      number[i].children[2].children[0].children[0].disabled = true;
    }
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
    getHeight();
    window.addEventListener("resize", getHeight);
  });
});

onUpdated(() => {
  getTableHeight();
  getHeight();
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
  window.removeEventListener("resize", getHeight);
});

function getHeight() {
  height.value = proxy.getSubFileHeight(proxy, "scrollbarRef", 125);
}

watch(
  () => selectedTotal.value,
  () => {
    if (selectedTotal.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 135 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 105 }];
    }
    getTableHeight();
  }
);

const isDisabled = ref(false);

if (selectedList.value.length === 0) {
  isDisabled.value = true;
}

watch(
  () => selectedList.value,
  (val) => {
    isDisabled.value = false;
    if (selectedList.value.length === 0) {
      getNumber();
      isDisabled.value = true;
    } else {
      // selectedList.value.forEach(item => {
      // })
    }
  }
);

const emit = defineEmits(["lMId","returnChangeMethod","setMyIdEmpty"]);

const methodList = ref([]);

function handleMethodChange() {
  proxy.$modal.confirm("更改方法将会删除填报表中的数据，确定要继续吗？").then(() => {
    changeOpen.value = true;
    changeMethod(lMId.value).then((res) => {
      methodList.value = res.data;
    });
  })
}

function changeDialogClose() {
  changeForm.value = { flagStatus: 0 };
}

function handleConfime() {
  changeForm.value.userGroupId = proxy.getItemByArray(
    methodList.value,
    "methodId",
    changeForm.value.methodId,
    "userGroupId"
  );
  changeForm.value.lMId = lMId.value;
  saveMethod(changeForm.value).then((res) => {
    if (!res.data) {
      proxy.$modal.confirm(res.msg).then(() => {
        changeForm.value.flagStatus = 1;
        handleConfime();
      });
    } else {
      if (res.data.close && res.data.close === 200) {
        emit("returnChangeMethod", { close: 200 });
        changeOpen.value = false;
        return;
      }
      emit("returnChangeMethod", {
        parentId: res.data.labMethod.parentId,
        lMId: res.data.labMethod.lMId,
        methodId: res.data.labMethod.methodId,
      });
      changeOpen.value = false;
    }
  });
}
</script>
